import os
import difflib
from collections import defaultdict


def read_txt_files_to_list(folder_path):
    """
    读取文件夹下所有txt文件，将每行内容合并成一个大的列表
    返回列表和文件行号映射信息
    """
    all_lines = []
    file_line_mapping = {}  # 记录每行对应的文件名和原行号

    # 获取文件夹下所有txt文件，按文件名排序确保一致性
    txt_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')]
    txt_files.sort()

    for filename in txt_files:
        file_path = os.path.join(folder_path, filename)
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
            for line_num, line in enumerate(lines, start=len(all_lines) + 1):
                all_lines.append(line)
                file_line_mapping[line_num] = {
                    'filename': filename,
                    'original_line_num': len(all_lines)  # 在当前文件中的行号
                }

    return all_lines, file_line_mapping


def generate_diff_report(folder1, folder2):
    """
    生成两个文件夹txt文件内容的差异报告
    """
    # 读取两个文件夹的内容
    list1, mapping1 = read_txt_files_to_list(folder1)
    list2, mapping2 = read_txt_files_to_list(folder2)

    # 使用difflib比较两个列表
    differ = difflib.Differ()
    diff_result = list(differ.compare(list1, list2))

    # 分析差异结果
    report = {
        'left_only': [],  # 只在左边存在的行
        'right_only': [],  # 只在右边存在的行
        'changed': [],  # 内容改变的行
        'common': [],  # 共同的行
        'summary': defaultdict(int)  # 差异统计
    }

    current_line_num = 0
    for line in diff_result:
        current_line_num += 1
        line_content = line[2:]  # 去掉前缀标记

        if line.startswith('- '):
            # 左边独有的行
            report['left_only'].append({
                'content': line_content,
                'line_num': current_line_num,
                'file_info': mapping1.get(current_line_num, {})
            })
            report['summary']['left_only'] += 1

        elif line.startswith('+ '):
            # 右边独有的行
            report['right_only'].append({
                'content': line_content,
                'line_num': current_line_num - report['summary']['left_only'] + report['summary']['right_only'],
                'file_info': mapping2.get(
                    current_line_num - report['summary']['left_only'] + report['summary']['right_only'], {})
            })
            report['summary']['right_only'] += 1

        elif line.startswith('? '):
            # 变化指示行（通常紧跟修改行）
            continue
        elif line.startswith('  '):
            # 共同的行
            report['common'].append({
                'content': line_content,
                'line_num': current_line_num - report['summary']['left_only'] + report['summary']['right_only'],
                'file_info': mapping1.get(current_line_num, {})
            })
            report['summary']['common'] += 1

    return report, diff_result


def print_detailed_report(report):
    """
    打印详细的差异报告
    """
    print("=" * 60)
    print("文件夹文本内容差异报告")
    print("=" * 60)

    # 统计信息
    print(f"\n📊 差异统计:")
    print(f"   共同行数: {report['summary']['common']}")
    print(f"   左边独有的行数: {report['summary']['left_only']}")
    print(f"   右边独有的行数: {report['summary']['right_only']}")

    # 左边独有的行
    if report['left_only']:
        print(f"\n❌ 左边文件夹独有的行 ({len(report['left_only'])}行):")
        for item in report['left_only']:
            print(f"   行号: {item['line_num']} | 文件: {item['file_info'].get('filename', '未知')}")
            print(f"   内容: {item['content'].rstrip()}")

    # 右边独有的行
    if report['right_only']:
        print(f"\n✅ 右边文件夹独有的行 ({len(report['right_only'])}行):")
        for item in report['right_only']:
            print(f"   行号: {item['line_num']} | 文件: {item['file_info'].get('filename', '未知')}")
            print(f"   内容: {item['content'].rstrip()}")

    # 原始diff格式输出
    print(f"\n📋 原始diff格式预览 (前20行):")
    print("=" * 40)
    for line in report['raw_diff'][:20]:
        print(line.rstrip())


def save_html_diff_report(folder1, folder2, list1, list2, output_file='diff_report.html'):
    """
    生成HTML格式的差异报告[6](@ref)
    """
    html_diff = difflib.HtmlDiff().make_file(
        list1, list2,
        fromdesc=f"文件夹: {folder1}",
        todesc=f"文件夹: {folder2}",
        context=True,
        numlines=3
    )

    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(html_diff)
    print(f"\n🌐 HTML格式报告已生成: {output_file}")


# 主程序
if __name__ == "__main__":
    batch_1 = "20250920"
    batch_2 = "20250930"
    # 设置要比较的两个文件夹路径
    folder1 = f"assets/{batch_1}/index"  # 替换为你的第一个文件夹路径
    folder2 = f"assets/{batch_2}/index"  # 替换为你的第二个文件夹路径

    # 检查文件夹是否存在
    if not os.path.exists(folder1) or not os.path.exists(folder2):
        print("错误: 指定的文件夹不存在，请检查路径")
        exit(1)

    print("开始比较文件夹内容...")

    # 生成差异报告
    report, raw_diff = generate_diff_report(folder1, folder2)
    report['raw_diff'] = raw_diff  # 保存原始diff结果

    # 打印报告
    print_detailed_report(report)

    # 生成HTML报告[6](@ref)
    list1, _ = read_txt_files_to_list(folder1)
    list2, _ = read_txt_files_to_list(folder2)
    save_html_diff_report(folder1, folder2, list1, list2)

    print(f"\n🎯 比较完成！")
    print(f"   总行数 - 左边: {len(list1)}, 右边: {len(list2)}")
    print(f"   差异行数: {report['summary']['left_only'] + report['summary']['right_only']}")